package com.java.study.invoker.enreka.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;


/**
 * 通过 RestTemplate 实现的负载，需要通过 Ribbon @LoadBalanced 实现
 */
@RestController
public class RestTemplateController {

    private static String SERVICE_NAME = "service-provider";


    @Autowired
    public RestTemplateBuilder builder;

    @Bean
    @LoadBalanced
//    @MyLoadBalanced
    RestTemplate restTemplate() {
        return builder.build();
    }

    /**
     * 注入
     */
    @Autowired
    private RestTemplate restTemplate;

    @Value("${server.port:8080}")
    private String port;


    @GetMapping("test")
    public String test() {

        String restData = restTemplate.getForObject("http://" + SERVICE_NAME + "/hello?name=" +
                UUID.randomUUID().toString(), String.class);
        return restData;
    }

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("uselb")
    public ServiceInstance getLB() {
        ServiceInstance serviceInstance = loadBalancerClient.choose(SERVICE_NAME);
        return serviceInstance;
    }
}
